package com.pvdnc.xdynamic.loader.module;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;

public class ModuleDir {
    private static final String TAG=ModuleDir.class.getSimpleName();

    private Context mContext;
    private final String mModuleName;

    public ModuleDir(Context context,String moduleName){
        mContext=context;
        mModuleName=moduleName;
    }

    private static File ensureDir(File parentDir,String childName)
            throws IllegalArgumentException,IOException {
        File childDir=new File(parentDir,childName);
        if(childDir.isFile())
            throw new IllegalArgumentException("path:"+childDir+" is a file");
        if(!childDir.exists()){
            Log.d(TAG,"attempt to create child dir:"+childName);
            if(!childDir.mkdirs())
                throw new IOException("fail to make dir:"+childDir);
        }
        Log.d(TAG,"ensured dir:"+childDir);
        return childDir;
    }

    public static File getModuleRootDir(Context context) {
        return context.getDir("module",Context.MODE_PRIVATE);
    }

    public File getModuleApkFile() throws IOException {
        return getModuleApkFile(getModuleDir());
    }

    public static File getModuleApkFile(File moduleDir){
        return new File(moduleDir,"module.apk");
    }

    public File getModuleDir() throws IOException {
        File rootDir=getModuleRootDir(mContext);
        File moduleDir=ensureDir(rootDir,mModuleName);
        Log.d(TAG,"module:"+mModuleName+"'s dir:"+moduleDir);
        return moduleDir;
    }

    private File getModuleSubDir(String name) throws IOException {
        File moduleDir=getModuleDir();
        File subDir=ensureDir(moduleDir,name);
        Log.d(TAG,"module:"+mModuleName+" 's "+name+" dir:"+subDir);
        return subDir;
    }

    public String getOptDir() throws IOException {
        return getModuleSubDir("optDex").getAbsolutePath();
    }

    public File getLibDir() throws IOException {
        return getModuleSubDir("lib");
    }

    public String getModuleDataDir() throws IOException {
        return getModuleSubDir("data").getAbsolutePath();
    }
}
